using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeFlow.Server.Dto;
using TradeFlow.Server.Models;
using SqlSugar;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service
{
    /// <summary>
    /// 业务单表体服务类
    /// </summary>
    public class JxBillListService : IApplicationService
    {
        private readonly SugarRepository<JxBillList> _repository;
        private readonly SugarRepository<JxBillHead> _headRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="headRepository"></param>
        /// <param name="localizer"></param>
        public JxBillListService(SugarRepository<JxBillList> repository, SugarRepository<JxBillHead> headRepository )
        {
            _repository = repository;
            _headRepository = headRepository;
        }

        /// <summary>
        /// 查询业务单表体分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetPagesAsync(JxBillListPageParam param)
        {
            try
            {
                var query = _repository.AsQueryable();
                
                // 根据参数进行条件筛选
                if (0<param.HeadId)
                {
                    query = query.Where(x => x.HeadId == param.HeadId);
                }
                if (!string.IsNullOrEmpty(param.Code))
                {
                    query = query.Where(x => x.Code.Contains(param.Code));
                }
                if (!string.IsNullOrEmpty(param.Name))
                {
                    query = query.Where(x => x.Name.Contains(param.Name));
                }

                // 执行分页查询
                var result = await query.OrderBy(x => x.SeqNo).ToPageListAsync(param.CurrentPage, param.PageSize);
                
                return new RestfulResult<object>()
                {
                    Data = result,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取所有业务单表体列表
        /// </summary>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetListAsync()
        {
            try
            {
                var list = await _repository.AsQueryable().ToListAsync();
                return new RestfulResult<object>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 根据表头ID获取表体列表
        /// </summary>
        /// <param name="headId"></param>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetByHeadIdAsync(long headId)
        {
            try
            {
                var list = await _repository.AsQueryable().Where(x => x.HeadId == headId).OrderBy(x => x.SeqNo).ToListAsync();
                return new RestfulResult<object>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 增加业务单表体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> AddAsync(JxBillList entity)
        {
            try
            {
                // 验证必填字段
                if (0<entity.HeadId)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "表头ID不能为空"
                    };
                }
                if (string.IsNullOrEmpty(entity.Code))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "商品信息不能为空"
                    };
                }
                if (entity.Qty <= 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数量无效"
                    };
                }
                if (!entity.Price.HasValue || entity.Price <= 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "价格无效"
                    };
                }

                // 检查表头是否存在且状态允许修改
                //if (long.TryParse(entity.HeadId, out long headId))
                //{
                    var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == entity.HeadId).FirstAsync();
                    if (headEntity == null)
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "表头记录不存在"
                        };
                    }
                    if (headEntity.Status == "已提交")
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "单据已提交，不能编辑"
                        };
                    }
                //}
                //else
                //{
                //    return new RestfulResult<object>()
                //    {
                //        Code = 0,
                //        Message = "表头ID格式错误"
                //    };
                //}


                // 计算金额
                entity.Amount = entity.Qty * (entity.Price ?? 0);

                // 获取最大序号
                var maxSeqNoObj = await _repository.AsQueryable().Where(x => x.HeadId == entity.HeadId).MaxAsync(x => (int?)x.SeqNo);
                int maxSeqNo = maxSeqNoObj ?? 0;
                entity.SeqNo = maxSeqNo + 1;

                // 保存表体数据
                await _repository.InsertAsync(entity);

                // 更新表头总金额
                await UpdateHeadTotalAmount(entity.HeadId);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 批量增加业务单表体
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> BatchAddAsync(List<JxBillList> entities)
        {
            try
            {
                if (entities == null || entities.Count == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据为空"
                    };
                }

                // 获取所有表头ID
                var headIds = entities.Select(x => x.HeadId).Distinct().ToList();
                if (headIds.Count > 1)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "批量添加必须使用相同表头"
                    };
                }

                long headIdStr = headIds[0];
                long headId = Convert.ToInt64(headIdStr);

                // 检查表头是否存在且状态允许修改
                var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == headId).FirstAsync();
                if (headEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "表头不存在"
                    };
                }
                if (headEntity.Status == "已提交")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据已提交，无法编辑"
                    };
                }

                // 获取最大序号
                var maxSeqNoObj = await _repository.AsQueryable().Where(x => x.HeadId == headIdStr).MaxAsync(x => (int?)x.SeqNo);
                int maxSeqNo = maxSeqNoObj ?? 0;

                // 处理每个明细
                for (int i = 0; i < entities.Count; i++)
                {
                    var entity = entities[i];
                    // 验证必填字段
                    // 移除对不存在的GoodsId的验证
                    if (entity.Qty <= 0)
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "数量无效"
                        };
                    }
                    if (!entity.Price.HasValue || entity.Price <= 0)
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "价格无效"
                        };
                    }

                    // 计算金额
                    entity.Amount = entity.Qty * entity.Price;
                    entity.SeqNo = maxSeqNo + i + 1;
                }

                // 保存表体数据
                await _repository.InsertRangeAsync(entities);

                // 更新表头总金额
                await UpdateHeadTotalAmount(headId);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新业务单表体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> UpdateAsync(JxBillList entity)
        {
            try
            {
                // 检查是否存在
                var oldEntity = await _repository.AsQueryable().Where(x => x.Id == entity.Id).FirstAsync();
                if (oldEntity == null)
                {
                    return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "数据不存在"
                };
                }

                // 检查表头是否允许修改
                var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(oldEntity.HeadId)).FirstAsync();
                if (headEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "表头不存在"
                    };
                }
                if (headEntity.Status == "已提交")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据已提交，无法编辑"
                    };
                }

                // 验证必填字段
                    // 移除对不存在的GoodsId的验证
                if (entity.Qty <= 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数量无效"
                    };
                }
                if (!entity.Price.HasValue || entity.Price <= 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "价格无效"
                    };
                }

                // 计算金额
                entity.Amount = entity.Qty * entity.Price;

                // 保持HeadId和SeqNo不变
                entity.HeadId = oldEntity.HeadId;
                entity.SeqNo = oldEntity.SeqNo;

                // 更新数据
                await _repository.UpdateAsync(entity);

                // 更新表头总金额
                await UpdateHeadTotalAmount(oldEntity.HeadId);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "更新成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "更新失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除业务单表体
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> DeleteAsync(List<long> ids)
        {
            try
            {
                // 获取要删除的记录
                var entities = await _repository.AsQueryable().Where(x => ids.Contains(x.Id)).ToListAsync();
                if (entities.Count == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 获取所有表头ID
                var headIds = entities.Select(x => x.HeadId).Distinct().ToList();

                foreach (var headId in headIds)
                {
                    // 检查表头是否允许修改
                    var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(headId)).FirstAsync();
                    if (headEntity != null && headEntity.Status == "已提交")
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "单据已提交，无法编辑"
                        };
                    }
                }

                // 删除数据 - 直接传入List<long>，不进行转换
                await _repository.DeleteAsync(x => ids.Contains(x.Id));

                // 更新所有相关表头的总金额
                foreach (var headId in headIds)
                {
                    await UpdateHeadTotalAmount(headId);
                }

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "删除失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新表头总金额
        /// </summary>
        /// <param name="headId"></param>
        private async Task UpdateHeadTotalAmount(long headId)
        {
            // 计算总金额
            decimal totalAmount = await _repository.AsQueryable().Where(x => x.HeadId == headId).SumAsync(x => x.Amount) ?? 0;
            
            // 更新表头
            await _headRepository.AsUpdateable().SetColumns(x => new JxBillHead { TotalAmount = totalAmount }).Where(x => x.Id == Convert.ToInt64(headId)).ExecuteCommandAsync();
        }
    }
}